"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 夏令时设置级联备备份延迟
Create At   : 2021/03/02
@zou_jialiang0505328126
Description :
Expect      :
    1.创建成功
    2.切换成功
    3.配置成功
    4.设置成功
    5.修改成功
    6.插入数据成功
    7.夏令时跳转
    8.5s备机未同步，5min备机同步
    9.更新成功
    10.5s备机未同步，5min备机同步
History     :
    Modified by @wan005 2021/3/23: 增加环境时区修复步骤
"""

import unittest
import time
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class RecoveryDelay(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.common = Common('PrimaryRoot')
        self.log.info('----Opengauss_Reliability_Dbsys_Case248.py 开始执行------')
        self.db_primary_root_node = Node(node='PrimaryRoot')
        self.db_standby_node =  \
            [Node(node='Standby1Root'), Node(node='Standby2Root')]
        self.comshsta = \
            [CommonSH('Standby1DbUser'), CommonSH('Standby2DbUser')]
        self.constant = Constant()
        self.tb_name = 'tb_247'
        self.node_name_pri = self.db_primary_root_node.sh('hostname').result()
        self.node_name_sta = self.db_standby_node[0].sh('hostname').result()
        self.current_local_zone_str = self.db_primary_root_node.sh(
            'ls -l /etc/localtime').result().split('->')[1]

        result = self.common.check_system_timezone(
            *('PrimaryRoot', 'Standby1Root', 'Standby2Root'))
        self.log.info(result)
        self.assertTrue(result)

        self.log.info('=====安装ntp服务=======')
        install_cmd = "yum install -y ntp && " \
                      "systemctl enable ntpd && systemctl start ntpd"
        result = self.db_primary_root_node.sh(install_cmd).result()
        self.log.info(result)
        result = self.db_standby_node[0].sh(install_cmd).result()
        self.log.info(result)

    def test_recoverydelay(self):
        self.log.info('-------将备节点切换为级联备---------')
        result = self.comshsta[0].buildStandby('-M cascade_standby')
        self.assertIn(self.constant.REBUILD_SUCCESS_MSG, result)
        result = self.comshsta[0].exec_refresh_conf()
        self.assertTrue(result)

        self.log.info('--------创建表-------')
        sql = f"drop table if exists {self.tb_name};" \
            f"create table {self.tb_name}(i int, s char(10));"
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result)

        self.log.info('-----设置recovery_min_apply_delay=5min----')
        result = self.commonshpri.executeGsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            'recovery_min_apply_delay=5min')
        self.assertTrue(result)

        self.log.info('-----设置设置数据库夏令时----')
        result = self.commonshpri.executeGsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            "TimeZone='America/New_York'", self.node_name_pri)
        self.assertTrue(result)
        result = self.commonshpri.executeGsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            "TimeZone='America/New_York'", self.node_name_sta)
        self.assertTrue(result)

        self.log.info('--------修改系统时区--------')
        zone_cmd = "ln -sf /usr/share/zoneinfo/America/New_York " \
                  "/etc/localtime;date -s '03/08/2020 01:59:00' && " \
                  "hwclock --systohc;service ntpd stop;" \
                  "ntpdate ntp.api.bz;service ntpd start"
        self.log.info(zone_cmd)
        result = self.db_primary_root_node.sh(zone_cmd).result()
        self.log.info(result)
        result = self.db_standby_node[0].sh(zone_cmd).result()
        self.log.info(result)

        self.log.info('--------等待主备一致------------')
        result = self.comshsta[1].check_data_consistency()
        self.assertTrue(result)
        for i in range(90):
            result = self.commonshpri.check_cascade_standby_consistency()
            if result:
                break
            time.sleep(20)
        self.assertTrue(result)

        self.log.info('--------插入数据-------')
        sql = f"select sysdate;" \
            f"insert into {self.tb_name} values(1,'test');"
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertIn('INSERT', result)

        self.log.info('--------等待1min，夏令时切换-------------------')
        time.sleep(60)
        result = self.db_standby_node[0].sh('date').result()
        self.log.info(result)
        self.assertIn('8 03:', result)
        result = self.db_primary_root_node.sh('date').result()
        self.log.info(result)
        self.assertIn('8 03:', result)

        self.log.info('----------等待5s查询备5min后查询备---------------')
        time.sleep(15)
        sql = f"select sysdate;select * from {self.tb_name};"
        result = self.comshsta[0].executDbSql(sql)
        self.log.info(result)
        self.assertIn('(0 rows)', result)
        time.sleep(400)
        result = self.comshsta[0].executDbSql(sql)
        self.log.info(result)
        self.assertIn('1 | test', result)

        self.log.info('--------更新数据-------')
        sql = f"select sysdate;" \
            f"update {self.tb_name} set i=5;"
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertIn('UPDATE', result)

        self.log.info('----------等待5s查询备5min后查询备---------------')
        time.sleep(15)
        sql = f"select sysdate;select * from {self.tb_name};"
        result = self.comshsta[0].executDbSql(sql)
        self.log.info(result)
        self.assertIn('1 | test', result)
        time.sleep(400)
        result = self.comshsta[0].executDbSql(sql)
        self.log.info(result)
        self.assertIn('5 | test', result)

    def tearDown(self):
        self.log.info('-----------------------------环境清理--------------------')
        self.log.info('-------------还原recovery_min_apply_delay----------')
        result = self.commonshpri.executeGsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            'recovery_min_apply_delay=0')
        self.log.info(result)

        self.log.info('-------还原数据库时区-------')
        self.commonshpri.executeGsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            "TimeZone='PRC'", self.node_name_pri)
        self.commonshpri.executeGsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            "TimeZone='PRC'", self.node_name_sta)

        self.log.info('--------还原集群-------')
        self.comshsta[0].buildStandby('-M standby')
        result = self.comshsta[0].exec_refresh_conf()
        self.log.info(result)

        self.log.info('-----------重启数据库-----------')
        result = self.commonshpri.stopDbCluster()
        self.log.info(result)
        result = self.commonshpri.startDbCluster()
        self.log.info(result)

        self.log.info('----------还原系统时区---------------')
        current = self.db_standby_node[1].sh(
            'date "+%m/%d/%Y %H:%M:%S"').result()
        self.log.info(current)
        zone_cmd = f"ln -sf {self.current_local_zone_str} " \
            f"/etc/localtime;date -s '{current}' && hwclock --systohc;" \
            f"service ntpd stop;ntpdate ntp.api.bz;service ntpd start"
        result = self.db_primary_root_node.sh(zone_cmd).result()
        self.log.info(result)
        result = self.db_standby_node[0].sh(zone_cmd).result()
        self.log.info(result)

        datecmd = f'date -s "{current}"'
        self.log.info(datecmd)
        for i in range(2):
            result = self.db_standby_node[i].sh(datecmd).result()
            self.log.info(result)

        time.sleep(5)
        self.log.info('--------删除表-------')
        sql = f"drop table if exists {self.tb_name};"
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.log.info('---Opengauss_Reliability_Dbsys_Case248.py 执行结束-------')